package com.authine.cloudpivot.ext.controller.organization;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.authine.cloudpivot.engine.api.model.organization.DepartmentModel;
import com.authine.cloudpivot.engine.api.model.organization.RoleModel;
import com.authine.cloudpivot.engine.api.model.organization.RoleUserModel;
import com.authine.cloudpivot.engine.api.model.organization.UserModel;
import com.authine.cloudpivot.engine.api.model.runtime.SelectionValue;
import com.authine.cloudpivot.engine.api.model.system.RelatedCorpSettingModel;
import com.authine.cloudpivot.engine.enums.type.OrgSyncType;
import com.authine.cloudpivot.engine.enums.type.OrgType;
import com.authine.cloudpivot.engine.enums.type.UnitType;
import com.authine.cloudpivot.web.api.controller.base.BaseController;
import com.authine.cloudpivot.web.api.dubbo.DubboConfigService;
import com.authine.cloudpivot.web.api.view.ResponseResult;
import com.authine.cloudpivot.web.api.view.organization.UserSelectionVO;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 二开角色相关接口
 *
 * @author shinka
 */
@Api(value = "EXTAPI::角色相关接口", tags = "01::EXTAPI::角色相关接口")
@RestController
@RequestMapping("/public/ext/role")
public class ExtRoleController extends BaseController {

    private static Logger log = LoggerFactory.getLogger(ExtRoleController.class);

    @Autowired
    private DubboConfigService dubboConfigService;

    @ApiOperation(value = "获取角色下用户")
    @GetMapping({"/users"})
    public ResponseResult<Object> queryUsers(@RequestParam(required = false, defaultValue = "") String roleId,
        @RequestParam() String departmentId) {
        log.info(" queryUsers departmentId = {}, roleCode={}", departmentId, roleId);
        try {
            // 查询角色
            RoleModel roleModel = dubboConfigService.getOrganizationFacade().getRole(roleId);
            String roleName = roleModel.getName();

            // 查询组织
            RelatedCorpSettingModel relatedCorpSettingModel = dubboConfigService.getSystemManagementFacade()
                .getRelatedCorpSettingModelByCorpId(roleModel.getCorpId());
            OrgType orgType = relatedCorpSettingModel.getOrgType();
            OrgSyncType syncType = relatedCorpSettingModel.getSyncType();

            // 获取角色下的用户
            List<String> userIdsList = queryRoleUsers(roleModel, departmentId);
            List<UserSelectionVO> userSelectionVOS = new ArrayList<>();
            if (CollectionUtils.isNotEmpty(userIdsList)) {
                // 查询用户信息
                Map<String, UserModel> userModelMap = dubboConfigService.getOrganizationFacade().getUsers(userIdsList);
                for (String key : userModelMap.keySet()) {
                    UserModel userModel = userModelMap.get(key);
                    // 选人控件属性值
                    UserSelectionVO userSelectionVO = new UserSelectionVO();
                    userSelectionVO.setId(userModel.getId());
                    userSelectionVO.setName(userModel.getName());
                    // copy properties
                    // BeanUtils.copyProperties(userModel, userSelectionVO);
                    // 获取部门
                    List<DepartmentModel> departmentsByUserId =
                        dubboConfigService.getOrganizationFacade().getDepartmentsByUserId(userModel.getId());
                    // 匹配
                    List<SelectionValue> departments = new ArrayList<>();
                    for (DepartmentModel dep : departmentsByUserId) {
                        if (!dep.getIsShow()) {
                            continue;
                        }
                        SelectionValue selectionValue = new SelectionValue();
                        selectionValue.setId(dep.getId());
                        selectionValue.setName(dep.getName());
                        selectionValue.setType(UnitType.DEPARTMENT);
                        departments.add(selectionValue);
                    }
                    userSelectionVO.setDepartments(departments);
                    userSelectionVO.setRoleName(roleName);
                    userSelectionVO.setRelatedOrgType(orgType);
                    userSelectionVO.setRelatedSyncType(syncType);
                    // list add
                    userSelectionVOS.add(userSelectionVO);
                }
            }
            return getOkResponseResult(userSelectionVOS, "根据发起人部门和预配置角色返回管理范围内用户成功");
        } catch (Exception e) {
            return getErrResponseResult(null, null, "根据发起人部门和预配置角色返回管理范围内用户失败：" + e.toString());
        }
    }

    private List<String> queryRoleUsers(RoleModel role, String deptId) {
        // 根据创建人部门查上级部门
        List<DepartmentModel> createrParentDepartments =
            dubboConfigService.getOrganizationFacade().getParentDepartments(deptId);

        List<String> users = new ArrayList<>();
        String roleId = role.getId();
        if (StringUtils.isNotEmpty(roleId)) {
            // 根据角色id查询角色下面的用户
            List<RoleUserModel> roleUserList = dubboConfigService.getOrganizationFacade().getRoleUsersByRoleId(roleId);
            if (CollectionUtils.isNotEmpty(roleUserList)) {
                for (DepartmentModel dm : createrParentDepartments) {
                    String parentId = dm.getId();
                    for (RoleUserModel roleUser : roleUserList) {
                        // 获取管理范围，管理范围包含传递的部门则返回用户ID
                        String ouScope = roleUser.getOuScope();
                        if (StringUtils.isNotEmpty(ouScope)) {
                            ouScope = ouScope.replace("[", "").replace("]", "").replaceAll("\"", "");
                            String[] arr = new String[] {ouScope};
                            if (ouScope.indexOf(",") > 0) {
                                arr = ouScope.split(",");
                            }
                            List<String> ouScopeList = Arrays.asList(arr);
                            if (ouScopeList.contains(parentId)) {
                                users.add(roleUser.getUserId());
                            }
                        }
                    }
                }
            } else {
                log.debug("根据角色ID查询数据为空：");
            }
        } else {
            log.debug("根据角色编码查询数据为空：");
        }
        return users;
    }

}
